from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from goods.models import SKU,GoodsCategory, SPUSpecification
from meiduo_admin.utils import PageNum
from meiduo_mall.apps.meiduo_admin.serializers.skus import SKUSerializer, GoodsCategorySerializer,SPUSpecificationSerializer


class SKUView(ModelViewSet):
    # 指定查询集
    queryset = SKU.objects.all()
    # 指定序列化器
    serializer_class = SKUSerializer
    # 指定分页器
    pagination_class = PageNum
    # 指定权限
    permission_classes = [IsAdminUser]

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword is None or keyword == '':
            return SKU.objects.all()
        else:
            return SKU.objects.filter(name__contains=keyword)



    # 获取三级分类信息
    @action(methods=['get'],detail=False)
    def categories(self,request):
        data = GoodsCategory.objects.filter(subs=None)
        ser = GoodsCategorySerializer(data,many=True)
        return Response(ser.data)
    def specs(self,request,pk):
        data = SPUSpecification.objects.filter(spu_id=pk)
        ser = SPUSpecificationSerializer(data,many=True)
        return Response(ser.data)